package com.sunday.common.mq.rocket.brave.study.base.e10_Brave_Trace;

import brave.Span.Kind;
import brave.messaging.ConsumerRequest;
import brave.propagation.Propagation.RemoteGetter;
import brave.propagation.Propagation.RemoteSetter;
import org.apache.rocketmq.common.message.MessageExt;

final class MessageConsumerRequest extends ConsumerRequest {
    static final RemoteGetter<MessageConsumerRequest> GETTER =
            new RemoteGetter<>() {
                @Override
                public Kind spanKind() {
                    return Kind.CONSUMER;
                }

                @Override
                public String get(MessageConsumerRequest request, String name) {
                    return MessageHeaders.getHeaderIfString(request.delegate, name);
                }

                @Override
                public String toString() {
                    return "properties::get";
                }
            };

    static final RemoteSetter<MessageConsumerRequest> SETTER =
            new RemoteSetter<>() {
                @Override
                public Kind spanKind() {
                    return Kind.CONSUMER;
                }

                @Override
                public void put(MessageConsumerRequest request, String name, String value) {
                    MessageHeaders.setHeader(request.delegate, name, value);
                }

                @Override
                public String toString() {
                    return "properties::put";
                }
            };

    final MessageExt delegate;

    MessageConsumerRequest(MessageExt delegate) {
        if (delegate == null) throw new NullPointerException("delegate == null");
        this.delegate = delegate;
    }

    @Override
    public Kind spanKind() {
        return Kind.CONSUMER;
    }

    @Override
    public Object unwrap() {
        return delegate;
    }

    @Override
    public String operation() {
        return "receive";
    }

    @Override
    public String channelKind() {
        return "queue";
    }

    @Override
    public String channelName() {
        String topic = delegate.getTopic();
        return topic != null ? topic : null;
    }

//    @Override
//    public String messageId() {
//        MessageProperties properties = delegate.getMessageProperties();
//        return properties != null ? properties.getMessageId() : null;
//    }
}
